import React, { useState, useEffect, useMemo } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import { Select, Form, message } from "antd";
import { hiprint } from "vue-plugin-hiprint";
import { getAllPrinter } from "@/utils/print.jsx";
import { setPrinterName, getPrinterName, getCurrentUser } from "@/utils/authority";
import CommonLoading from "@/components/CommonLoading";
import { manualDelivery, batchPrintByQualifiedOutbound, getCoFcTemplateByIdsOutbound } from "../service";
import { isJSON } from "@/utils/utils.jsx";
import { isEmpty } from "lodash";
import styles from "./index.module.less";

const printKey = "code";
const printQueenArr = [];
let isPrinting = false; // 是否正在打印， 正在打印的数组

let hiprintTemplate,
	printedArr = [],
	runner;

const PrintModal = ({ visible, onCancel, ids, checkedRows }) => {
	const [form] = Form.useForm();
	const [data, setData] = useState([]); //打印机列表
	const [loading, setLoading] = useState(false);
	const [printData, setPrintData] = useState([]);
	const [template, setTemplate] = useState([]);

	//打印的公用参数
	const commonParams = useMemo(() => {
		return {
			el: "#kuaimaiiframeprint",
			appId: "1666316938957",
			itemsId: "69",
			userId: getCurrentUser()?.id + ""
		};
	}, []);

	//打印执行逻辑
	const printUnicode = () => {
		const obj = printQueenArr.shift();
		if (!obj) {
			isPrinting = false;
			printedArr = [];
			return;
		}
		const { kmTemplateId, zjf_pick_label, printer } = obj || {};
		return new Promise(() => {
			const parms = {
				...commonParams,
				id: kmTemplateId,
				data: { zjf_pick_label },
				usbList: [printer],
				callback: () => {
					zjf_pick_label?.[0]?.uniqueCode && printedArr.push(zjf_pick_label[0].uniqueCode);
					printUnicode();
				}
			};
			KMTEMPLATE.printLabelNoPreview(parms);
		});
	};

	useEffect(() => {
		if (visible) {
			console.log("visible", visible);
			if (!runner) {
				runner = new TaskRunner();
				runner.setConcurrency(1); // 同时执行数量
			}
			getAllPrinter(value => {
				const printname = getPrinterName();
				if (printname && value.includes(printname)) {
					form.setFieldsValue({
						printer: printname
					});
				} else {
					form.resetFields();
				}
				setData(value);
			});
			getPrintDataFunc();
		}
	}, [visible]);

	//获取打印数据
	const getPrintDataFunc = async () => {
		const param = ["w1773190846682595330"]; //checkedRows.map(e => e.outboundNo);
		const { data } = await batchPrintByQualifiedOutbound(param);
		console.log("获取打印数据", data);
		// setTemplate(data);
		// setPrintData(
		// 	checkedRows.map(e => ({
		// 		uniqueCode: e[printKey]
		// 	}))
		// );
	};
	//回调相同逻辑处理
	const callBack = () => {
		// statusChange(printedArr);
		// refresh(printedArr);
		printedArr = [];
	};

	//打印队列渲染输出
	const realPrint = (runner, done, printData, printer) => {
		hiprintTemplate = new hiprint.PrintTemplate({ template });

		console.log("template", template);

		hiprintTemplate.on("printSuccess", function () {
			printData.uniqueCode && printedArr.push(printData.uniqueCode);
			console.log("printedArr", printedArr);
			if (!runner?.tasks?.list?.length || printedArr?.length == 10) {
				callBack();
			}
			done();
		});
		hiprintTemplate.on("printError", function () {
			if (!runner?.tasks?.list?.length) {
				callBack();
			}
			done();
		});
		hiprintTemplate.print2(printData, { printer });
	};

	//获取打印数据推入队列
	const onOk = () => {
		if (!printData?.length) {
			return message.info("打印数据为空");
		}

		form.validateFields().then(({ printer }) => {
			const task = [];
			printData.map(item => {
				task.push(done => {
					realPrint(runner, done, item, printer);
				});
			});
			runner.addMultiple(task);
			message.success(`即将打印${printData.length}个合格证，请等待`);
			onCancel();
		});
	};

	// 设置打印机名称
	const handlePrinterName = name => {
		setPrinterName(name);
	};

	const options =
		!isEmpty(data) &&
		data.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		));

	return (
		<CommonModal
			title={{ title: "合格证打印" }}
			visible={visible}
			onCancel={onCancel}
			width="456px"
			onOk={onOk}
			okText="打印"
			minHeight={138}
		>
			<Form form={form} name="common-printer-select">
				<Form.Item label="订单数量" name="orderCount">
					<div>{ids.length}</div>
				</Form.Item>
				<Form.Item label="打印机" name="printer" rules={[{ required: true, message: "请先选择打印机" }]}>
					<Select placeholder="请选择打印机" onChange={handlePrinterName}>
						{options}
					</Select>
				</Form.Item>
				{/* <Form.Item>
					<div className={styles.goodsNum}>
						<span>打印唯一码数量：</span>
						<span>{printData.length}</span>
					</div>
				</Form.Item> */}
			</Form>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default PrintModal;
